import torch
import itertools
from utils.image_pool import ImagePool
from .base_model import BaseModel
from .cyclegan import networks
import numpy as np
from  numpy.fft import fft2,fftshift
# from .lightcnn import network as lightcnn
from .cyclegan.sintestapi import sinTestApi
from .cyclegan.testapi import get_frequency

# import mypymath
# import time
from PIL import Image
from data.base_dataset import  get_transform
from torchvision import transforms
def change_fre(F):
    ans = 100 - F
    if ans <= 0:
        ans = 0
    return ans  
        
class CycleGANSABFFTModel(BaseModel):
    """
    This class implements the CycleGAN model, for learning image-to-image translation without paired data.

    The model training requires '--dataset_mode unaligned' dataset.
    By default, it uses a '--netG resnet_9blocks' ResNet generator,
    a '--netD basic' discriminator (PatchGAN introduced by pix2pix),
    and a least-square GANs objective ('--gan_mode lsgan').

    CycleGAN paper: https://arxiv.org/pdf/1703.10593.pdf
    """
    @staticmethod
    def modify_commandline_options(parser, is_train=True):
        """Add new dataset-specific options, and rewrite default values for existing options.

        Parameters:
            parser          -- original option parser
            is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.

        Returns:
            the modified parser.

        For CycleGAN, in addition to GAN losses, we introduce lambda_A, lambda_B, and lambda_identity for the following losses.
        A (source domain), B (target domain).
        Generators: G_A: A -> B; G_B: B -> A.
        Discriminators: D_A: G_A(A) vs. B; D_B: G_B(B) vs. A.
        Forward cycle loss:  lambda_A * ||G_B(G_A(A)) - A|| (Eqn. (2) in the paper)
        Backward cycle loss: lambda_B * ||G_A(G_B(B)) - B|| (Eqn. (2) in the paper)
        Identity loss (optional): lambda_identity * (||G_A(B) - B|| * lambda_B + ||G_B(A) - A|| * lambda_A) (Sec 5.2 "Photo generation from paintings" in the paper)
        Dropout is not used in the original CycleGAN paper.
        """
        
        # parser.set_defaults(frequency=True)
        # parser.add_argument('--num_classes', type=int, default=3, help='the architecture situation of model')
        # parser.add_argument('--pretrained_model', type=str, default="lightcnn", help='the architecture of pretrained model')
        # parser.add_argument('--pretrained_path', type=str, default="lightcnn", help='the path of pretrained model')
        # parser.add_argument('--pretrained_ndf', type=int, default=128, help='the number of features of output ')
        # parser.add_argument('--pretrained_output_nc', type=int, default=256, help='the number of features of output ')

        parser.set_defaults(no_dropout=True)  # default CycleGAN did not use dropout
        parser.add_argument('--inputs', type=str, default='0', help='the moudal of input data ')
        parser.add_argument('--outputs', type=str, default='1', help='the moudal ofoutput data ')
        # parser.add_argument('--bins', type=int, default=16, help='the number of features of output ')
        # parser.add_argument('--cal_mode', type=str, default='linear', help='the mode of caculating')
        parser.add_argument('--slope', type=int, default=0, help='slope parameter')
        # parser.add_argument('--frequency', type=bool, default=True, help='the mode of caculating')
        # if is_train:
        parser.add_argument('--use_inception',action='store_true', help='The switch of inception')
        parser.add_argument('--lambda_A', type=float, default=1.0, help='weight for cycle loss (A -> B -> A)')
        parser.add_argument('--lambda_B', type=float, default=1.0, help='weight for cycle loss (B -> A -> B)')
        parser.add_argument('--lambda_fre', type=float, default=0, help='weight for preTrained Discriminator loss')
        parser.add_argument('--lambda_identity', type=float, default=0.5, help='use identity mapping. Setting lambda_identity other than 0 has an effect of scaling the weight of the identity mapping loss. For example, if the weight of the identity loss should be 10 times smaller than the weight of the reconstruction loss, please set lambda_identity = 0.1')
        return parser
    
    def display_opt_init(opt):
        # parser.add_argument('--inputs', type=str, default='img', help='the moudal of input data ')
        opt.__setattr__('inputs','S0')
        opt.__setattr__('outputs','SD')
        # opt.__setattr__('cal_mode','linear')
        opt.__setattr__('slope',0)
        opt.__setattr__('lambda_fre',0)
        return opt
    def display_init(self,_dict):
        
        transform = get_transform(self.opt, grayscale=(self.opt.input_nc == 1))
        # pil_img = Image.fromarray(np.uint8(_dict['img']))
        # _dict[self.opt.inputs] = transform(pil_img)
        # c,h,w = _dict[self.opt.inputs].shape
        # _dict[self.opt.inputs] = _dict[self.opt.inputs].reshape(1,c,h,w)
        _dict[self.opt.inputs+'_paths'] = "ZedCamera"
        for b in _dict['boxes']:
            face = transform(Image.fromarray(np.uint8(_dict['img'][b[1]:b[3],b[0]:b[2],:])))
            c,h,w = face.shape
            if self.opt.inputs in _dict.keys():
                _dict[self.opt.inputs] = torch.cat((_dict[self.opt.inputs],face.unsqueeze(0)),0)
            else:
                _dict[self.opt.inputs] = face.unsqueeze(0)
        return _dict

    def __init__(self, opt):
        """Initialize the CycleGAN class.

        Parameters:
            opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions
        """
        
        BaseModel.__init__(self, opt)
        # specify the training losses you want to print out. The training/test scripts will call <BaseModel.get_current_losses>
        # self.loss_names = ['D_A', 'G_A', 'cycle_A', 'idt_A', 'D_B', 'G_B', 'cycle_B', 'idt_B']
        # if self.opt.controller == 'test':
        #     self.opt.lambda_fre = 0
        self.opt.frequency = not self.opt.lambda_fre == 0
        self.A = self.opt.inputs
        self.B = self.opt.outputs
        self.TestApi = sinTestApi(opt)
        # self.last_val_best = 0
        self.visuale_param()
        self.dualGAN = False

        # specify the models you want to save to the disk. The training/test scripts will call <BaseModel.save_networks> and <BaseModel.load_networks>.
        if self.isTrain or self.opt.use_inception:
            # self.model_names = ['G_A', 'G_B', 'D_A', 'D_B']
            self.model_names = ['G_SAB','G_SBA', 'D_SA', 'D_SB',]
        else:  # during test time, only load Gs
            self.model_names = ['G_SAB','G_SBA']

        # define networks (both Generators and discriminators)
        # The naming is different from those used in the paper.
        # Code (vs. paper): G_A (G), G_B (F), D_A (D_Y), D_B (D_X)
        self.netG_SAB = networks.define_G(opt.input_nc + opt.slope, opt.output_nc , opt.ngf, opt.netG, opt.norm,
                                        not opt.no_dropout, opt.init_type, opt.init_gain, self.gpu_ids)
        
        self.netG_SBA = networks.define_G(opt.output_nc + opt.slope, opt.input_nc , opt.ngf, opt.netG, opt.norm,
                                        not opt.no_dropout, opt.init_type, opt.init_gain, self.gpu_ids)

        self.criterionPredD = torch.nn.L1Loss()
        self.criterionGAN = networks.GANLoss(opt.gan_mode).to(self.device)  # define GAN loss.
        self.criterionCycle = torch.nn.L1Loss()
        self.criterionIdt = torch.nn.L1Loss()
        
        if self.isTrain or self.opt.use_inception:  # define discriminators
            self.netD_SB = networks.define_D(opt.output_nc, opt.ndf, opt.netD,
                                            opt.n_layers_D, opt.norm, opt.init_type, opt.init_gain, self.gpu_ids)

            self.netD_SA = networks.define_D(opt.input_nc, opt.ndf, opt.netD,
                                            opt.n_layers_D, opt.norm, opt.init_type, opt.init_gain, self.gpu_ids)
            # self.netD_light.define_lightcnn(opt)

            # self.netD_SA2 = networks.define_D(opt.input_nc, opt.ndf, opt.netD,
            #                                 opt.n_layers_D, opt.norm, opt.init_type, opt.init_gain, self.gpu_ids)
            # if self.opt.val:
            #     self.last_val_best = 0
            
            # self.nepoch = self.opt.n_epochs + self.opt.n_epochs_decay
            # self.fac = self.epoch/(self.nepoch+1)
            if opt.lambda_identity > 0.0:  # only works when input and output images have the same number of channels
                assert(opt.input_nc == opt.output_nc)
            self.fake_SA_pool = ImagePool(opt.pool_size)  # create image buffer to store previously generated images
            self.fake_SB_pool = ImagePool(opt.pool_size)  # create image buffer to store previously generated images
            # self.fake_S2_SA_pool = ImagePool(opt.pool_size)  # create image buffer to store previously generated images
            
        if self.isTrain:
            if self.opt.continue_train:
                self.epoch = self.opt.epoch_count
            self.optimizer_G = torch.optim.Adam(itertools.chain(self.netG_SAB.parameters(), self.netG_SBA.parameters()), lr=opt.lr, betas=(opt.beta1, 0.999))
            self.optimizer_D = torch.optim.Adam(itertools.chain(self.netD_SA.parameters(), self.netD_SB.parameters()), lr=opt.lr, betas=(opt.beta1, 0.999))
            self.optimizers.append(self.optimizer_G)
            self.optimizers.append(self.optimizer_D)
            
        # else:
        #     self.fid_net = network_tianyu.inception()
            # _model = opt.model
            # _isTrain = opt.isTrain
            # _ndf = opt.ndf
            # _outpu_nc = opt.output_nc
            # opt.model = opt.pretrained_model
            # opt.isTrain = False
            # opt.ndf = opt.pretrained_ndf
            # opt.output_nc = opt.pretrained_output_nc
            # self.netD_light = create_model(opt)      # create a model given opt.model and other options
            # self.netD_light.setup(opt)
            # self.netD_light.load_pretrained_networks(opt.pretrained_path)
            # opt.model = _model
            # opt.isTrain = _isTrain
            # opt.ndf = _ndf
            # opt.output_nc = _outpu_nc
    def visuale_param(self):
        self.TestApi.init(self.isTrain)
        if self.isTrain:
            self.loss_names = ["G_SAB","cycle_SAB","idt_SAB",
                                "G_SBA","cycle_SBA","idt_SBA",
                                "D_SA","D_SB","G","mean_G",
                                ]
        else:
            self.loss_names = ["SB_SSIM","SAB_SSIM","SB_PSNR","SAB_PSNR"]
            self.loss_names += ["mean_SB_PSNR","mean_SAB_PSNR"]
            self.loss_names += ["mean_SB_SSIM","mean_SAB_SSIM"]
            if self.opt.use_inception:
                self.loss_names += ["SB_FID","SAB_FID","mean_SB_FID","mean_SAB_FID","mean_SB_DFID"]
                # self.count_mean_SB_FID=NewAverageMeter()
                # self.count_mean_SAB_FID=AverageMeter()
            # if self.opt.controller == 'test':
            # self.count_mean_S012D_SSIM=NewAverageMeter()
        # self.count_ppaGSBA=AverageMeter()
        # self.count_ppaGSAB=AverageMeter()
        # self.count_ppaRSBA=AverageMeter()
        # self.count_ppaRSAB=AverageMeter()
        # if self.opt.lambda_fre != 0:
        # if self.opt.frequency:
        self.loss_names +=["mean_Frequency_SB"]
        
        
        visual_names_S1A = ['real_SA', 'fake_SBA', ]
        visual_names_S1B = ['real_SB', 'fake_SAB']
        # if self.isTrain:
        visual_names_S1B += ['rec_SAB', 'rec_SBA']
        # visual_names_S1A += ['real_SA_h', 'fake_SBA_h', 'rec_SBA_h']
        # visual_names_S1B += ['real_SB_h', 'fake_SAB_h', 'rec_SAB_h']
        
        self.visual_names = visual_names_S1A + visual_names_S1B  # combine visualizations for A and B
        pass
    
    # def cal_slope(self,data,directions=2,mode='constant',):
    #     if directions == 0:
    #         return data.to(self.device)
    #     x = F.pad(data,(1,1,1,1,0,0),mode,value=0)
    #     x1 = x[:,:,1:-1,1:-1]-x[:,:,1:-1,0:-2]
    #     x2 = x[:,:,1:-1,1:-1]-x[:,:,0:-2,1:-1]
    #     if directions == 2:
    #         return torch.cat((x[:,:,1:-1,1:-1],x1,x2),dim=1).to(self.device)
    #     if directions == 4:
    #         x3 = x[:,:,1:-1,1:-1]-x[:,:,0:-2,0:-2]
    #         x4 = x[:,:,1:-1,1:-1] - x[:,:,0:-2,2:]
    #         # test = torch.cat((x[:,:,1:-1,1:-1],x1,x2,x3,x4),dim=1).to(self.device)
    #         # recoverFslope(test)
    #         return torch.cat((x[:,:,1:-1,1:-1],x1,x2,x3,x4),dim=1).to(self.device)
        
    def set_input(self, input):
        """Unpack input data from the dataloader and perform necessary pre-processing steps.

        Parameters:
            input (dict): include the data itself and its metadata information.

        The option 'direction' can be used to swap domain A and domain B.
        """
        # AtoB = self.opt.direction == 'AtoB'
        # self.real_A = input['A' if AtoB else 'B'].to(self.device)
        # self.real_B = input['B' if AtoB else 'A']self.device)
        # self.image_paths = input['A_paths' if AtoB else 'B_paths']
        if self.A in input.keys():
            self.real_SA = input[self.A].to(self.device)
            self.image_paths = input[self.A+'_paths']
        else:
            self.real_SA = None
            self.image_paths = None
            
        if self.B in input.keys():
            self.dualGAN = True
            self.real_SB = input[self.B].to(self.device)
        # self.real_S2 = input['S2'].to(self.device)
        
        # if self.opt.lambda_fre != 0:
        self.real_SA_F = input[self.A+'_F'][:,0,:,:]
        if self.B+'_F' in input.keys():
            self.real_SB_F = input[self.B+'_F'][:,0,:,:]
        
        if "isTrain" in input.keys():
            if self.isTrain != input["isTrain"]:
                self.isTrain = input["isTrain"]
                self.visuale_param()

    def forward(self):
        """Run forward pass; called by both functions <optimize_parameters> and <test>."""
        # self.fake_B = self.netG_A(self.real_A)  # G_A(A)
        # self.rec_A = self.netG_B(self.fake_B)   # G_B(G_A(A))
        # self.fake_A = self.netG_B(self.real_B)  # G_B(B)
        # self.rec_B = self.netG_A(self.fake_A)   # G_A(G_B(B))
        if self.real_SA is not None:
            self.fake_SAB = self.netG_SAB(self.real_SA, self.opt.slope)
            self.rec_SBA = self.netG_SBA(self.fake_SAB["generation"], self.opt.slope)
            # if self.isTrain:
            if self.dualGAN:
                self.fake_SBA = self.netG_SBA(self.real_SB, self.opt.slope)
                self.rec_SAB = self.netG_SAB(self.fake_SBA["generation"], self.opt.slope)
        
        if self.opt.use_inception:
            self.real_SA_Fea = self.netD_SB(self.real_SA)
            self.real_SB_Fea = self.netD_SB(self.real_SB)
            self.fake_SB_Fea = self.netD_SB(self.fake_SAB["generation"])
            
            # self.loss_SB_FID = self.criterionGAN.loss(real_SB_Fea,fake_SB_Fea)
            # self.loss_SAB_FID = self.criterionGAN.loss(real_SA_Fea,real_SB_Fea)
        
    def backward_D_basic(self, netD, real, fake):
        """Calculate GAN loss for the discriminator

        Parameters:
            netD (network)      -- the discriminator D
            real (tensor array) -- real images
            fake (tensor array) -- images generated by a generator

        Return the discriminator loss.
        We also call loss_D.backward() to calculate the gradients.
        """
        # Real
        pred_real = netD(real)
        loss_D_real = self.criterionGAN(pred_real, True)
        # Fake
        pred_fake = netD(fake.detach())
        loss_D_fake = self.criterionGAN(pred_fake, False)
        # Combined loss and calculate gradients
        loss_D = (loss_D_real + loss_D_fake) * 0.5
        if self.isTrain:
            loss_D.backward()
        return loss_D

    def backward_D_SA(self):
        """Calculate GAN loss for discriminator D_SA"""
        fake_SA = self.fake_SA_pool.query(self.fake_SBA["generation"])
        self.loss_D_SA = self.backward_D_basic(self.netD_SA, self.real_SA, fake_SA)

    def backward_D_SB(self):
        """Calculate GAN loss for discriminator D_SB"""
        fake_SAB = self.fake_SB_pool.query(self.fake_SAB["generation"])
        self.loss_D_SB = self.backward_D_basic(self.netD_SB, self.real_SB, fake_SAB)
        
    def backward_Frequency(self):
        # def get_frequency(src):
        #     res = []
        #     for i in range(src.shape[0]):
        #         res.append(fftshift(fft2(src[i,:,:])))
        #     return torch.tensor(np.array(res))
        
        # starttime1 = time.time()
        fake_SB_F = get_frequency(self.fake_SAB["generation"].contiguous().cpu().detach().numpy()[:,0,:,:])
        rec_SA_F = get_frequency(self.rec_SBA["generation"].contiguous().cpu().detach().numpy()[:,0,:,:])
        
        self.loss_Frequency_fake_SB = self.criterionPredD(fake_SB_F,self.real_SB_F)
        self.loss_Frequency_rec_SB = self.criterionPredD(rec_SA_F,self.real_SA_F)
        
        self.loss_Frequency = (self.loss_Frequency_fake_SB + self.loss_Frequency_rec_SB).to(self.device)
        if self.isTrain:
            rec_SB_F = get_frequency(self.rec_SAB.contiguous().cpu().detach().numpy()[:,0,:,:])
            fake_SA_F = get_frequency(self.fake_SBA.contiguous().cpu().detach().numpy()[:,0,:,:])
            
            self.loss_Frequency_fake_SA = self.criterionPredD(fake_SA_F,self.real_SA_F)
            self.loss_Frequency_rec_SA = self.criterionPredD(rec_SB_F,self.real_SB_F)
            self.loss_Frequency += (self.loss_Frequency_fake_SA + self.loss_Frequency_rec_SA).to(self.device)
        
        # self.count_Frequency_SB.update(change_fre(self.loss_Frequency_fake_SB.item()))
        
    
    def backward_G(self):
        """Calculate the loss for generators G_A and G_B"""
        
        # self.loss_frequency = self.
        # fake_SB_F = mypymath.fft2d()
        # self.loss_frequency = self.criterionPredD()
        # fake_SB_F = mypymath.fft2d(1,self.fake_SAB.shape[0],self.fake_SAB.contiguous().cpu().detach().numpy()[:,0,:,:])
        if self.opt.lambda_fre != 0 and self.opt.controller == 'train':
            self.backward_Frequency()
        
        if self.isTrain:
            lambda_fre = self.opt.lambda_fre # * (self.fac)
            lambda_idt = self.opt.lambda_identity
            lambda_A = self.opt.lambda_A #* (1 - self.fac)
            lambda_B = self.opt.lambda_B #* (1 - self.fac)
            # Identity loss
            if lambda_idt > 0:
                # G_A should be identity if real_B is fed: ||G_A(B) - B||
                self.idt_SAB = self.netG_SAB(self.fake_SAB, self.opt.slope)
                self.loss_idt_SAB = self.criterionIdt(self.idt_SAB, self.real_SB) * lambda_B * lambda_idt
                # G_B should be identity if real_A is fed: ||G_B(A) - A||
                self.idt_SBA= self.netG_SBA(self.real_SA, self.opt.slope)
                self.loss_idt_SBA = self.criterionIdt(self.idt_SBA, self.real_SA) * lambda_A * lambda_idt
                
            else:
                self.loss_idt_SAB = 0
                self.loss_idt_SBA = 0
            
            self.loss_G_SAB = self.criterionGAN(self.netD_SB(self.fake_SAB["generation"]), True)
            # GAN loss D_B(G_B(B))
            self.loss_G_SBA = self.criterionGAN(self.netD_SA(self.fake_SBA["generation"]), True)
            
            # GAN loss D_A(G_A(A))
            # self.loss_G_SA2 = self.criterionGAN(self.netD_S2(self.fake_SA2), True)
            # GAN loss D_B(G_B(B))
            # self.loss_G_S20 = self.criterionGAN(self.netD_S20(self.fake_S20), True)
            
            # Forward cycle loss || G_B(G_A(A)) - A||
            self.loss_cycle_SBA = self.criterionCycle(self.rec_SBA["generation"], self.real_SA) * lambda_A
            # Backward cycle loss || G_A(G_B(B)) - B||
            self.loss_cycle_SAB = self.criterionCycle(self.rec_SAB["generation"], self.real_SB) * lambda_B
            
            # Forward cycle loss || G_B(G_A(A)) - A||
            # self.loss_cycle_S20 = self.criterionCycle(self.rec_S20, self.real_SA) * lambda_A
            # Backward cycle loss || G_A(G_B(B)) - B||
            # self.loss_cycle_S2 = self.criterionCycle(self.rec_SA2, self.real_S2) * lambda_B
            
            # combined loss and calculate gradients
            self.loss_G = self.loss_G_SAB + self.loss_G_SBA + self.loss_cycle_SBA + self.loss_cycle_SAB + self.loss_idt_SAB + self.loss_idt_SBA
            if lambda_fre != 0:
                self.loss_G += lambda_fre * self.loss_Frequency
            
            self.loss_G.backward()
            self.count_G.update(self.loss_G.item())
            self.loss_mean_G = self.count_G.avg
            
            # self.cal_score()
        # self.loss_G_S2 = self.loss_G_SA2 + self.loss_G_S20 + self.loss_cycle_S20 + self.loss_cycle_S2 + self.loss_idt_SA_S2 + self.loss_idt_S2_SA
        # self.loss_G = 0.5 * self.loss_G_SB + 0.5 * self.loss_G_S2

    def optimize_parameters(self):
        """Calculate losses, gradients, and update network weights; called in every training iteration"""
        # forward
        self.forward()      # compute fake images and reconstruction images.
        # G_A and G_B
        self.set_requires_grad([self.netD_SA, self.netD_SB], False)  # Ds require no gradients when optimizing Gs
        # self.optimizer_G.zero_grad()  # set G_A and G_B's gradients to zero
        self.optimizer_G.zero_grad()
        # self.optimizer_G_SA2.zero_grad()
        self.backward_G()             # calculate gradients for G_A and G_B
        # self.optimizer_G.step()       # update G_A and G_B's weights
        self.optimizer_G.step()       # update G_A and G_B's weights
        # self.optimizer_G_SA2.step()
        # D_A and D_B
        self.set_requires_grad([self.netD_SA, self.netD_SB], True)
        self.optimizer_D.zero_grad()   # set D_A and D_B's gradients to zero
        # self.optimizer_D_SA2.zero_grad()   # set D_A and D_B's gradients to zero
        self.backward_D_SA()      # calculate gradients for D_A
        # self.backward_D_S20()      # calculate gradients for D_A
        self.backward_D_SB()      # calculate graidents for D_B
        # self.backward_D_S2()      # calculate graidents for D_B
        self.optimizer_D.step()  # update D_A and D_B's weights
        # self.optimizer_D_SA2.step()  # update D_A and D_B's weights
        # self.cal_score()
        
    def cal_score(self):
        if not self.isTrain:
            self.backward_Frequency()
    #         self.backward_G() 
        # self.fake_SAB = recoverFslope(self.fake_SAB,1,-1)
        # self.real_SA = recoverFslope(self.real_SA,1,-1)
       
        # if not self.isTrain:
           
        # self.fake_S02 = normal(self.fake_S02,1,0)  
        # gt_SA = image2gt(self.real_SA, self.opt.bins,self.opt.cal_mode)
        # pred_SBA = image2gt(self.fake_SBA, self.opt.bins,self.opt.cal_mode)

        # rec_SBA = image2gt(self.rec_SBA, self.opt.bins,self.opt.cal_mode)
        
        # gt_SB = image2gt(self.real_SB, self.opt.bins,self.opt.cal_mode)
        # pred_SB = image2gt(self.fake_SAB, self.opt.bins,self.opt.cal_mode)
        # rec_SB = image2gt(self.rec_SAB, self.opt.bins,self.opt.cal_mode)
        
        # self.real_SA_h = gt_SA[0,:,:]/np.max(gt_SA)*255
        # self.fake_SBA_h = pred_SBA[0,:,:]/np.max(pred_SBA)*255
        # self.rec_SBA_h = rec_SBA[0,:,:]/np.max(rec_SBA)*255
        # self.real_SB_h = gt_SB[0,:,:]/np.max(gt_SB)*255
        # self.fake_SAB_h = pred_SB[0,:,:]/np.max(pred_SB)*255
        # self.rec_SAB_h = rec_SB[0,:,:]/np.max(rec_SB)*255

        # self.count_ppaGSBA.update_np(per_pix_acc(gt_SA,pred_SBA))
        # self.count_ppaGSAB.update_np(per_pix_acc(gt_SB,pred_SB))
        # self.count_ppaRSBA.update_np(per_pix_acc(gt_SA,rec_SBA))
        # self.count_ppaRSBA.update_np(per_pix_acc(gt_SB,rec_SB))
       
        # self.loss_per_pix_acc_G_SBA = self.count_ppaGSBA.avg  # per_pix_acc(gt_SA,pred_SBA)
        # self.loss_per_pix_acc_G_SAB = self.count_ppaGSAB.avg  # per_pix_acc(gt_SB,pred_SB)
        
        # self.loss_per_pix_acc_rec_SBA = self.count_ppaRSBA.avg  # per_pix_acc(gt_SA,rec_SBA)
        # self.loss_per_pix_acc_rec_SAB = self.count_ppaRSBA.avg  # per_pix_acc(gt_SB,rec_SB)

        pass
    def iter_end(self):
        
        records = {}
        # if self.opt.frequency:
        records['loss_Frequency_fake_SB'] = self.loss_Frequency_fake_SB
        records['loss_Frequency_real_SAB'] = self.criterionPredD(self.real_SA_F,self.real_SB_F)
        
        if self.opt.controller == 'test' or not self.isTrain:
            if self.dualGAN:
                records['dualGAN'] = self.dualGAN
                records['real_SA'] = self.real_SA
                records['real_SB'] = self.real_SB
                records['fake_SAB'] = self.fake_SAB["generation"]
                if self.opt.use_inception:
                    records['real_SA_Fea'] = self.real_SA_Fea
                    records['real_SB_Fea'] = self.real_SB_Fea
                    records['fake_SB_Fea'] = self.fake_SB_Fea
            records["image_paths"] = self.image_paths
        out = self.TestApi.record(records)
        
        if self.opt.controller == 'test' or not self.isTrain:
            if self.dualGAN:
                self.loss_mean_SB_PSNR = out["count_mean_SB_PSNR"]
                self.loss_mean_SAB_PSNR = out["count_mean_SAB_PSNR"]
                self.loss_mean_SB_SSIM = out["count_mean_SB_SSIM"]
                self.loss_mean_SAB_SSIM = out["count_mean_SAB_SSIM"]
                if self.opt.use_inception:
                    self.loss_mean_SB_FID = out["count_mean_SB_FID"]
                    self.loss_mean_SAB_FID = out["count_mean_SAB_FID"]
                    self.loss_mean_SB_DFID = out["count_mean_SB_DFID"]
                
                self.TOP100p_mean_SB_SSIM = out["count_mean_SB_SSIM"]
        # if self.opt.frequency:
        self.loss_mean_Frequency_SB = out["count_Frequency_SB"]
        self.fake_SAB = self.fake_SAB["generation"]
        self.rec_SBA = self.rec_SBA["generation"]
        if self.dualGAN:
            self.fake_SBA = self.fake_SBA["generation"]
            self.rec_SAB = self.rec_SAB["generation"]

    def epoch_end(self):
        records = self.TestApi.statistic()
        if not self.isTrain:

            self.TOP10p_mean_SB_SSIM = records["TOP10p_mean_SB_SSIM"]
            self.TOP50p_mean_SB_SSIM = records["TOP50p_mean_SB_SSIM"]

        # if self.opt.isTrain:
        #     self.epoch+=1
            # self.fac = self.epoch/(self.nepoch+1)
    def val_save(self,param):
        self.val_best = getattr(self,param)
        if self.last_val_best[param] < self.val_best:
            self.last_val_best[param] = self.val_best
            return True
        return False

    def display_proc(self,_dict):
        """
            为了展示控制器准备的函数接口，用户可以自己定义
        """
        # image)
        tran = transforms.ToPILImage()
        if len(_dict['boxes'])>0:
            B,C,H,W = self.fake_SAB.shape
            for i,b in enumerate(_dict['boxes']):
                face = tran(self.fake_SAB[i,:,:,:].contiguous().cpu().detach().squeeze(0))
                h = b[3] - b[1]
                w = b[2] - b[0]
                
                _dict['box_img'][b[1]:b[3],b[0]:b[2],0] = np.array(face.resize((w,h)))
                _dict['box_img'][b[1]:b[3],b[0]:b[2],1] = np.array(face.resize((w,h)))
                _dict['box_img'][b[1]:b[3],b[0]:b[2],2] = np.array(face.resize((w,h)))
                _dict['SD'] = self.fake_SAB
                
            pass
            
        return _dict

class AverageMeter(object):
    def __init__(self):
        self.reset()

    def reset(self):
        self.val = 0
        self.avg = 0
        self.sum = 0
        self.count = 0

    def update(self, val, n=1):
        self.val = val
        self.sum += val * n
        self.count += n
        self.avg = self.sum / self.count
    
    def update_np(self,val):
        self.sum = np.sum(val,0)
        self.count += val.shape[0]
        self.avg = self.sum / self.count